//
//  MTNewEditQuestionVC.m
//  met
//
//  Created by 李晓俊 on 2019/6/23.
//  Copyright © 2019 李晓俊. All rights reserved.
//

#import "MTNewEditQuestionVC.h"
#import "SensitiveWordTools.h"
#import "CustomTextView.h"
#import "MTNewCardCreateVC.h"
#import "MTQuestionAnswerVC.h"

#import "MTCardListCollectionViewCell.h"
@interface MTNewEditQuestionVC ()<UICollectionViewDelegate,UICollectionViewDataSource,CLLocationManagerDelegate>
@property (nonatomic, strong) UICollectionView *collectionView;
@property (nonatomic, strong) UIButton *lookBtn;

@property (strong, nonatomic)  UIView *bottomView;
//@property (nonatomic, strong) NSMutableArray *dataArr;
@property (nonatomic,strong) NSMutableArray *sensitiveArr;
@end

@implementation MTNewEditQuestionVC

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
//    self.isLike = @"1";
    [self dayOnce];
    [self customNavItem];
    self.sensitiveArr = [NSMutableArray new];
    
}


- (void)initUI{
    [self.view addSubview:self.collectionView];
    self.collectionView.frame = self.view.bounds;
    [self.view addSubview:self.lookBtn];
    
 
}
- (UIButton *)lookBtn{
    if (_lookBtn == nil) {
        CGRect rect = CGRectMake(12, kScreenHeight - 59 - 12 - BottomHeight, kScreenWidth - 24 , 59);
        _lookBtn = [[UIButton alloc] initWithFrame:rect text:@"修改漂流卡" textcolor:HEXCOLOR(0x333333) backgroundcolor:HEXCOLOR(0xFEF45C) fontSize:26 haveCorner:NO];
        _lookBtn.titleLabel.font = CLRudeCircleTextFont(18);
        _lookBtn.layer.cornerRadius = 10;
        _lookBtn.layer.masksToBounds = YES;
        _lookBtn.layer.borderWidth = 2;
        _lookBtn.layer.borderColor = KBlackColor.CGColor;
        [_lookBtn addTarget:self action:@selector(lookClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _lookBtn;
}

#pragma mark - 定制导航条内容
- (void)customNavItem {
    UIButton *rightBtn = [[UIButton alloc] initWithFrame:CGRectZero text:@"查看效果"  textcolor:KBlackColor backgroundcolor:nil fontSize:15 haveCorner:NO];
    [rightBtn addTarget:self action:@selector(rightAction) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn];
    
    UIButton *rightBtn2 = [[UIButton alloc] initWithFrame:CGRectZero text:@"删除"  textcolor:KBlackColor backgroundcolor:nil fontSize:15 haveCorner:NO];
    [rightBtn2 addTarget:self action:@selector(rightAction2) forControlEvents:UIControlEventTouchUpInside];
//    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightBtn2];
    //间隙
    UIBarButtonItem *fixedSpaceBarButtonItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    fixedSpaceBarButtonItem.width = 20;
    self.navigationItem.rightBarButtonItems = @[[[UIBarButtonItem alloc] initWithCustomView:rightBtn],fixedSpaceBarButtonItem,[[UIBarButtonItem alloc] initWithCustomView:rightBtn2]];
    
}
#pragma mark - 按钮事件
- (void)rightAction2{
    //    MTCardHelpVC *vc = GetViewControllerInStoryboard(@"Card", @"MTCardHelpVC");
    //    [self.navigationController pushViewController:vc animated:YES];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            [self.view maketishiToast:@"删除成功"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc removeStoryByStoryId:self.storyId];
}
    
    
- (void)rightAction{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            
            NSMutableArray *ar = [NSMutableArray new];
            for (int i= 0 ;i < self.dataArr.count ; i ++ ){
                NSDictionary *dic = [self.dataArr objectAtIndex:i];
                NSMutableDictionary *info = [NSMutableDictionary new];
                if ([[dic objectForKey:@"question"] length] > 0) {
                    info[@"questionText"] = dic[@"question"];
                    info[@"remarks"] = dic[@"answerfail"];
                    info[@"sequence"] = @"";
                    
                    NSMutableArray *answerList = [NSMutableArray new];
                    
                    NSMutableDictionary *anserInfo = [NSMutableDictionary new];
                    anserInfo[@"answerText"] = dic[@"answer1"];
                    if ([dic[@"isLike"] isEqualToString:@"1"]) {
                        anserInfo[@"isTrue"] = @"1";
                    }else {
                        anserInfo[@"isTrue"] = @"0";
                    }
                    if (i == self.dataArr.count -1) {
                        anserInfo[@"resultType"] = @"2";
                    }else {
                        anserInfo[@"resultType"] = @"0";
                    }
                    
                    [answerList addObject:anserInfo];
                    
                    NSMutableDictionary *anserInfo2 = [NSMutableDictionary new];
                    anserInfo2[@"answerText"] = dic[@"answer2"];
                    if ([dic[@"isLike"] isEqualToString:@"1"]) {
                        anserInfo2[@"isTrue"] = @"0";
                    }else {
                        anserInfo2[@"isTrue"] = @"1";
                    }
                    anserInfo2[@"resultType"] = @"1";
                    [answerList addObject:anserInfo2];
                    
                    anserInfo[@"sequence2"] = @"1";
                    anserInfo2[@"sequence2"] = @"2";
                    
                    info[@"answerList"] = [self gibberishArray:answerList];
                    [ar addObject:info];
                }
            }
            
            if (ar.count == 0) {
                MTOkTishiView *okView = [[MTOkTishiView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
                okView.content.text = @"至少设置一个问题 ";
                okView.bgView.backgroundColor = KMainPinkColor;
                okView.goButClick = ^(NSString *  s) {
                };
                [[UIApplication sharedApplication].keyWindow addSubview:okView];
                return;
            }
            for (int i = 0; i < ar.count; i ++) {
                NSMutableDictionary *dic = [ar objectAtIndex:i];
                dic[@"sequence"] = [NSString stringWithFormat:@"%d",i+1];
                [ar replaceObjectAtIndex:i withObject:dic];
            }
            
            
            MTQuestionAnswerVC *vc = [[MTQuestionAnswerVC alloc] init];
            vc.dataArr = ar;
            vc.leftName = KUSER.nickName;
            vc.rightName = @"TA";
            
            vc.leftUrl = [NSString stringWithFormat:@"%@",KUSER.portraitIm];
            vc.sceneUrl = [NSString stringWithFormat:@"%@",[data objectForKey:@"data"]];
            vc.sex = [NSString stringWithFormat:@"%@",KUSER.sex];

            //    vc.isLook = @"1";
            //    vc.storyId = self.storyId;
            //    vc.storyVersion = self.storyVersion;
            [self.navigationController pushViewController:vc animated:YES];
                    
        }else {
            [self.view maketishiToast:data];
        }
    };
    
    [acc sceneFind];
    
   
}

//将一个数组元素顺序打乱
- (NSMutableArray *)gibberishArray:(NSArray *)array{
    NSMutableArray *arr = [NSMutableArray  arrayWithCapacity:array.count];
    NSMutableArray *tempArr = [[NSMutableArray alloc] initWithArray:array];
    int count = (int)array.count;
    int randCount = 0;//索引
    int nowCount = 0;//当前数组的元素个数
    
    for (;count != 0; ) {
        nowCount = (int)tempArr.count;//当前数组的元素个数
        count = nowCount;
        if (nowCount != 0) {
            randCount = (arc4random() % nowCount);
            [arr addObject:tempArr[randCount]];
            tempArr[randCount] = tempArr.lastObject;
            [tempArr removeLastObject];
        }
    }
    return arr;
}



//敏感词
- (void)findWords{
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        if (code == 1) {
            NSDate *nowDate = [NSDate date];
            NSUserDefaults *dataUser = [NSUserDefaults standardUserDefaults];
            [dataUser setObject:nowDate forKey:@"mingancinowDate"];
            
            NSMutableArray *ar = [NSMutableArray new];
            NSArray *arr = data;
            for (NSDictionary *dic in arr) {
                [ar addObject:[NSString stringWithFormat:@"%@",[dic objectForKey:@"content"]]];
            }
            [dataUser setObject:[ar copy] forKey:@"sensitiveArr"];
            self.sensitiveArr = ar;
            [dataUser synchronize];
            [SensitiveWordTools sharedInstance].sensitiveArr = self.sensitiveArr;
        }else {
            [self.view maketishiToast:data];
        }
    };
    [acc findSensitiveWords];
}
//一天只执行一次
- (void)dayOnce {
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    //    NSLog(@"之前时间：%@", [userDefault objectForKey:@"nowDate"]);//之前存储的时间
    //    NSLog(@"现在时间%@",[NSDate date]);//现在的时间
    NSDate *now = [NSDate date];
    NSDate *agoDate = [userDefault objectForKey:@"mingancinowDate"];
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    
    NSString *ageDateString = [dateFormatter stringFromDate:agoDate];
    NSString *nowDateString = [dateFormatter stringFromDate:now];
    //    NSLog(@"日期比较：之前：%@ 现在：%@",ageDateString,nowDateString);
    
    if ([ageDateString isEqualToString:nowDateString]) {
        //        DLog(@"一天就显示一次");
    }else{
        // 需要执行的方法写在这里
        [self findWords];
    }
}



#pragma mark - colloectionviewdelegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    if (self.dataArr.count == 15) {
        return 15;
    }
    return self.dataArr.count+1;
}
- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    return 1;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    MTCardListCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"cardCell" forIndexPath:indexPath];
    if (indexPath.row >= self.dataArr.count) {
        [cell.nameBut setTitle:@"新增一个问题" forState:UIControlStateNormal];
        [cell.nameBut setTitleColor:TextTiTleColor forState:UIControlStateNormal];
        
        //        cell.bgView.image = [UIImage imageNamed:@"虚线"];
        cell.nameBut.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
        cell.contentView.layer.borderColor = KBlackColor.CGColor;
        cell.contentView.layer.borderWidth = 3;
        ///暂时显示，以后有图标
        return cell;
    }
    
    NSDictionary *dic = self.dataArr[indexPath.row];
    NSString *str = [dic objectForKey:@"question"];
    if (str.length == 0) {
        [cell.nameBut setImage:[UIImage imageNamed:@"bianjibiaoge"] forState:UIControlStateNormal];
        [cell.nameBut setTitle:[NSString stringWithFormat:@"  编辑问题%ld",indexPath.row + 1] forState:UIControlStateNormal];
    }else {
        [cell.nameBut setImage:nil forState:UIControlStateNormal];
        [cell.nameBut setTitle:[NSString stringWithFormat:@"%ld.%@",indexPath.row + 1,str] forState:UIControlStateNormal];
    }
    cell.bgView.image = nil;
    [cell.nameBut setTitleColor:KBlackColor forState:UIControlStateNormal];
    
    cell.nameBut.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
    
    ///暂时显示，以后有图标
    cell.contentView.layer.borderColor = KBlackColor.CGColor;
    cell.contentView.layer.borderWidth = 3;
    return cell;
}
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    return CGSizeMake((kScreenWidth - 40 - 30) / 3, 45);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 15;
}
// 该方法是设置一个section的上左下右边距
- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    return UIEdgeInsetsMake(15, 15, 15, 15);
}

- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    MTNewCardCreateVC *vc = GetViewControllerInStoryboard(@"Card", @"MTNewCardCreateVC");
    if (indexPath.row >= self.dataArr.count) {
        vc.insertInfo = ^(NSMutableDictionary *  dic) {
            [self.dataArr addObject:dic];
            [self.collectionView reloadData];
        };
        //        vc.deleteInfo  = ^(NSMutableDictionary *  dic) {
        //            [self.dataArr removeObjectAtIndex:tag];
        //            [self setBottom];
        //        };
    }else {
        NSInteger tag = indexPath.row;
        vc.dic = [self.dataArr objectAtIndex:tag];
        vc.insertInfo = ^(NSMutableDictionary *  dic) {
            [self.dataArr replaceObjectAtIndex:indexPath.row withObject:dic];
            [self.collectionView reloadData];
        };
        vc.deleteInfo  = ^(NSMutableDictionary *  dic) {
            [self.dataArr removeObjectAtIndex:tag];
            [self.collectionView reloadData];
            //        [self.dataArr replaceObjectAtIndex:tag withObject:dic];
        };
    }
    vc.sensitiveArr = self.sensitiveArr;
    [self.navigationController pushViewController:vc animated:YES];
}


#pragma mark - get
- (UICollectionView *)collectionView{
    if (!_collectionView) {
        UICollectionViewFlowLayout * layout = [[UICollectionViewFlowLayout alloc] init];
        layout.minimumLineSpacing = 15;
        layout.minimumInteritemSpacing = 15;
        _collectionView = [[UICollectionView alloc] initWithFrame:CGRectZero collectionViewLayout:layout];
        _collectionView.delegate = self;
        _collectionView.dataSource = self;
        _collectionView.backgroundColor = WhiteColor;
        //        _collectionView.bounces = NO;
        _collectionView.showsVerticalScrollIndicator = NO;
        [_collectionView registerClass:[MTCardListCollectionViewCell class] forCellWithReuseIdentifier:@"cardCell"];
        //        [_collectionView registerClass:[MTCardListHeaderView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"cardHeader"];
    }
    return _collectionView;
}
- (void)lookClick {
    NSMutableArray *arr = [NSMutableArray new];
    for (NSDictionary *dic in self.dataArr) {
        if ([[dic objectForKey:@"question"] length] > 0) {
            [arr addObject:dic];
        }
    }
    if (arr.count == 0) {
        MTOkTishiView *okView = [[MTOkTishiView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        okView.content.text = @"至少设置一个问题 ";
        okView.bgView.backgroundColor = KMainPinkColor;
        okView.goButClick = ^(NSString *  s) {
        };
        [[UIApplication sharedApplication].keyWindow addSubview:okView];
    }else {
        [self addStory];
    }
}
- (void)addStory{
    NSMutableArray *ar = [NSMutableArray new];
    for (int i= 0 ;i < self.dataArr.count ; i ++ ){
        NSDictionary *dic = [self.dataArr objectAtIndex:i];
        NSMutableDictionary *info = [NSMutableDictionary new];
        if ([[dic objectForKey:@"question"] length] > 0) {
            info[@"questionText"] = [self replacernk:dic[@"question"]];
            info[@"remarks"] = dic[@"answerfail"];
            info[@"sequence"] = @"";
            
            
            NSMutableArray *answerList = [NSMutableArray new];
            
            NSMutableDictionary *anserInfo = [NSMutableDictionary new];
            anserInfo[@"answerText"] = [self replacernk:dic[@"answer1"]];
            if ([dic[@"isLike"] isEqualToString:@"1"]) {
                anserInfo[@"isTrue"] = @"1";
            }else {
                anserInfo[@"isTrue"] = @"0";
            }
            if (i == self.dataArr.count -1) {
                anserInfo[@"resultType"] = @"2";
            }else {
                anserInfo[@"resultType"] = @"0";
            }
            
            [answerList addObject:anserInfo];
            
            NSMutableDictionary *anserInfo2 = [NSMutableDictionary new];
            anserInfo2[@"answerText"] = [self replacernk:dic[@"answer2"]];
            if ([dic[@"isLike"] isEqualToString:@"1"]) {
                anserInfo2[@"isTrue"] = @"0";
            }else {
                anserInfo2[@"isTrue"] = @"1";
            }
            anserInfo2[@"resultType"] = @"1";
            [answerList addObject:anserInfo2];
            
            anserInfo[@"sequence2"] = @"1";
            anserInfo2[@"sequence2"] = @"2";
            
            info[@"answerList"] = [self gibberishArray:answerList];
            [ar addObject:info];
        }
    }
    
    if (ar.count == 0) {
        MTOkTishiView *okView = [[MTOkTishiView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
        okView.content.text = @"至少设置一个问题 ";
        okView.bgView.backgroundColor = KMainPinkColor;
        okView.goButClick = ^(NSString *  s) {
        };
        [[UIApplication sharedApplication].keyWindow addSubview:okView];
        return;
    }
    for (int i = 0; i < ar.count; i ++) {
        NSMutableDictionary *dic = [ar objectAtIndex:i];
        dic[@"sequence"] = [NSString stringWithFormat:@"%d",i+1];
        [ar replaceObjectAtIndex:i withObject:dic];
    }
    //
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    AccountService *acc = [AccountService getObject];
    acc.httpRequestResultBlock = ^(id data,int code){
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        if (code == 1) {
            
            //            [self.view maketicket2Toast:@"10"];
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                MTOkTishiView *okView = [[MTOkTishiView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight)];
                okView.content.text = @"恭喜你！卡牌修改成功\n快去“我的”查看吧 ";
                okView.bgView.backgroundColor = KMainColor;
                okView.goButClick = ^(NSString *  s) {
                    [self.navigationController popViewControllerAnimated:YES];
                };
                [[UIApplication sharedApplication].keyWindow addSubview:okView];
            });
            
        }else {
            [self.view maketishiToast:data];
        }
    };
    NSString *lat = @"";
    NSString *lng = @"";
//    if (self.cityName.length > 0) {
//
//        lat =  [NSString stringWithFormat:@"%f",self.coordinate.latitude] ;
//        lng = [NSString stringWithFormat:@"%f",self.coordinate.longitude];
//    }
    
    [acc updateStory:@"" storyId:self.storyId angelId:@"1" questionList:ar lat:lat  lng:lng];
}
- (NSString *)replacernk:(NSString *)encodedImageStr {
    encodedImageStr = [encodedImageStr stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    encodedImageStr = [encodedImageStr stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    encodedImageStr = [encodedImageStr stringByReplacingOccurrencesOfString:@"\t" withString:@""];
    encodedImageStr = [encodedImageStr stringByReplacingOccurrencesOfString:@" " withString:@""];
    return encodedImageStr;
}
@end
